<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑推荐模板' : '新增推荐模板'"
    width="600px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="handleClose"
    custom-class="datav-dialog"
    :modal-class="'datav-modal'"
  >
    <dv-decoration-8 class="dialog-header-decoration" :reverse="true" />
    <dv-border-box-8 class="datav-form-container" :dur="5">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="template-form"
      >
      <el-form-item label="模板标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入模板标题" />
      </el-form-item>
      
      <el-form-item label="模板内容" prop="template">
        <el-input
          v-model="form.template"
          type="textarea"
          :rows="4"
          placeholder="请输入模板内容"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="标签" prop="tagsArray">
        <el-tag
          v-for="tag in form.tagsArray"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleTagClose(tag)"
          class="tag-item"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputTagVisible"
          ref="tagInputRef"
          v-model="inputTagValue"
          class="tag-input"
          size="small"
          @keyup.enter="handleTagConfirm"
          @blur="handleTagConfirm"
          maxlength="10"
          placeholder="请输入标签，最多10个字符"
        />
        <el-button 
          v-else 
          class="button-new-tag" 
          size="small" 
          @click="showTagInput"
          :disabled="form.tagsArray.length >= 5"
        >
          <el-icon><Plus /></el-icon> 添加标签
        </el-button>
        <div class="form-tip">每个标签长度限制1-10个字符，最多5个标签</div>
      </el-form-item>
      
      <el-form-item label="预览图" prop="imgPreview">
        <div class="image-upload-container">
          <el-upload
            class="template-image-uploader"
            action="#"
            :http-request="uploadPreviewImage"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            accept="image/jpeg,image/png,image/gif"
          >
            <img v-if="form.imgPreview" :src="form.imgPreview" class="preview-image" />
            <div v-else class="image-uploader-placeholder">
              <el-icon><Plus /></el-icon>
              <div>点击上传预览图</div>
              <div class="image-tips">建议尺寸300×400px</div>
            </div>
          </el-upload>
        </div>
      </el-form-item>
      
      <el-form-item label="Word文档" prop="fileid">
        <div class="file-upload-container">
          <el-upload
            class="template-file-uploader"
            action="#"
            :http-request="uploadWordFile"
            :show-file-list="false"
            :before-upload="beforeWordUpload"
            accept=".doc,.docx"
          >
            <el-button type="primary" class="tech-button tech-button--primary" :loading="wordUploading">
              <el-icon><Upload /></el-icon>
              {{ form.fileid ? '重新上传Word' : '上传Word文档' }}
            </el-button>
          </el-upload>
          <div v-if="form.fileid" class="file-uploaded">
            <el-icon><Document /></el-icon>
            <span>已上传Word文档</span>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="PDF文档" prop="fileidPdf">
        <div class="file-upload-container">
          <el-upload
            class="template-file-uploader"
            action="#"
            :http-request="uploadPdfFile"
            :show-file-list="false"
            :before-upload="beforePdfUpload"
            accept=".pdf"
          >
            <el-button type="primary" class="tech-button tech-button--primary" :loading="pdfUploading">
              <el-icon><Upload /></el-icon>
              {{ form.fileidPdf ? '重新上传PDF' : '上传PDF文档' }}
            </el-button>
          </el-upload>
          <div v-if="form.fileidPdf" class="file-uploaded">
            <el-icon><Document /></el-icon>
            <span>已上传PDF文档</span>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="启用状态" prop="enable">
        <el-switch
          v-model="form.enable"
          active-text="启用"
          inactive-text="禁用"
          class="tech-switch"
        />
      </el-form-item>
      </el-form>
    </dv-border-box-8>
    
    <template #footer>
      <dv-border-box-1 class="datav-dialog-footer-box">
        <div class="datav-dialog-footer">
          <el-button @click="handleClose" class="tech-button">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting" class="tech-button tech-button--primary">
            保存
          </el-button>
        </div>
      </dv-border-box-1>
    </template>
    <dv-decoration-8 class="dialog-footer-decoration" />
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Document } from '@element-plus/icons-vue'
import { app, ensureLogin } from '../../utils/cloudbase'
import dayjs from 'dayjs'

export default {
  name: 'RecommendTemplateFormDialog',
  components: {
    Plus,
    Upload,
    Document
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => null
    }
  },
  emits: ['update:visible', 'refresh'],
  setup(props, { emit }) {
    // 表单引用
    const formRef = ref(null)
    const tagInputRef = ref(null)
    
    // 对话框可见性
    const dialogVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val)
    })
    
    // 标签输入相关
    const inputTagVisible = ref(false)
    const inputTagValue = ref('')
    
    // 是否为编辑模式
    const isEdit = computed(() => !!props.editData)
    
    // 上传状态
    const wordUploading = ref(false)
    const pdfUploading = ref(false)
    const submitting = ref(false)
    
    // 标签选项
    const tagOptions = ref([
      '简历', '求职', '应届生', '专业', '技术', '管理', '销售', '市场', '金融', 'IT'
    ])
    
    // 表单数据
    const form = reactive({
      _id: '',
      id: '',
      title: '',
      template: '',
      tagsArray: [],
      imgPreview: '',
      fileid: '',
      fileidPdf: '',
      enable: true
    })
    
    // 表单验证规则
    const rules = {
      title: [
        { required: true, message: '请输入模板标题', trigger: 'blur' },
        { min: 1, max: 30, message: '长度在1到30个字符之间', trigger: 'blur' }
      ],
      template: [
        { required: true, message: '请输入模板内容', trigger: 'blur' }
      ],
      tagsArray: [
        { 
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              callback(new Error('请至少添加一个标签'))
            } else if (value.length > 5) {
              callback(new Error('最多选择5个标签'))
            } else if (value.some(tag => tag.length > 10)) {
              callback(new Error('标签长度不能超过10个字符'))
            } else {
              callback()
            }
          }, 
          trigger: 'change' 
        }
      ],
      imgPreview: [
        { required: true, message: '请上传预览图', trigger: 'change' }
      ],
      fileid: [
        { 
          validator: (rule, value, callback) => {
            if (!value && !form.fileidPdf) {
              callback(new Error('Word文档和PDF文档至少上传一种'))
            } else {
              callback()
            }
          }, 
          trigger: 'change' 
        }
      ],
      fileidPdf: [
        { 
          validator: (rule, value, callback) => {
            if (!value && !form.fileid) {
              callback(new Error('Word文档和PDF文档至少上传一种'))
            } else {
              callback()
            }
          }, 
          trigger: 'change' 
        }
      ]
    }
    
    // 重置表单
    const resetForm = () => {
      form._id = ''
      form.id = ''
      form.title = ''
      form.template = ''
      form.tagsArray = []
      form.imgPreview = ''
      form.fileid = ''
      form.fileidPdf = ''
      form.enable = true
      
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        // 填充表单数据
        form._id = newVal._id || ''
        form.id = newVal.id || ''
        form.title = newVal.title || ''
        form.template = newVal.template || ''
        form.tagsArray = newVal.tags ? newVal.tags.split(',') : []
        form.imgPreview = newVal.imgPreview || ''
        form.fileid = newVal.fileid || ''
        form.fileidPdf = newVal.fileidPdf || ''
        form.enable = newVal.enable !== undefined ? newVal.enable : true
      } else {
        // 重置表单
        resetForm()
      }
    }, { immediate: true })
    
    // 关闭对话框
    const handleClose = () => {
      if (wordUploading.value || pdfUploading.value || submitting.value) {
        ElMessageBox.confirm('当前有上传任务正在进行，确定要关闭吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dialogVisible.value = false
          resetForm()
        }).catch(() => {})
      } else {
        dialogVisible.value = false
        resetForm()
      }
    }
    
    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        ElMessage.error('上传文件只能是图片格式!')
        return false
      }
      
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
        return false
      }
      
      return true
    }
    
    // Word文档上传前验证
    const beforeWordUpload = (file) => {
      const isWord = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                     file.type === 'application/msword'
      const isLt10M = file.size / 1024 / 1024 < 10
      
      if (!isWord) {
        ElMessage.error('上传文件只能是Word文档格式!')
        return false
      }
      
      if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB!')
        return false
      }
      
      return true
    }
    
    // PDF文档上传前验证
    const beforePdfUpload = (file) => {
      const isPdf = file.type === 'application/pdf'
      const isLt10M = file.size / 1024 / 1024 < 10
      
      if (!isPdf) {
        ElMessage.error('上传文件只能是PDF格式!')
        return false
      }
      
      if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB!')
        return false
      }
      
      return true
    }
    
    // 生成文件路径
    const generateFilePath = (prefix, fileExt) => {
      const date = dayjs()
      const datePath = date.format('YYYYMMDD')
      const timePath = date.format('HHmmss')
      return `${prefix}/${datePath}/${timePath}${fileExt}`
    }
    
    // 上传预览图
    const uploadPreviewImage = async (options) => {
      try {
        const file = options.file
        
        // 转换为Base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = async (e) => {
          const base64Content = e.target.result.split(',')[1]
          const folder = generateFilePath('image', '')
          
          await ensureLogin()
          
          const res = await app.callFunction({
            name: 'admin-file-upload',
            data: {
              fileContent: base64Content,
              fileName: file.name,
              folder
            }
          })
          
          if (res.result && res.result.code === 0) {
            form.imgPreview = res.result.data.fileUrl || res.result.data.fileId
            ElMessage.success('预览图上传成功')
          } else {
            ElMessage.error(res.result?.message || '预览图上传失败')
          }
        }
      } catch (error) {
        console.error('上传预览图失败:', error)
        ElMessage.error('预览图上传失败')
      }
    }
    
    // 上传Word文档
    const uploadWordFile = async (options) => {
      try {
        wordUploading.value = true
        const file = options.file
        
        // 转换为Base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = async (e) => {
          const base64Content = e.target.result.split(',')[1]
          const folder = generateFilePath('resumeAuto', '')
          
          await ensureLogin()
          
          const res = await app.callFunction({
            name: 'admin-file-upload',
            data: {
              fileContent: base64Content,
              fileName: file.name,
              folder
            }
          })
          
          if (res.result && res.result.code === 0) {
            form.fileid = res.result.data.fileId
            ElMessage.success('Word文档上传成功')
          } else {
            ElMessage.error(res.result?.message || 'Word文档上传失败')
          }
        }
      } catch (error) {
        console.error('上传Word文档失败:', error)
        ElMessage.error('Word文档上传失败')
      } finally {
        wordUploading.value = false
      }
    }
    
    // 上传PDF文档
    const uploadPdfFile = async (options) => {
      try {
        pdfUploading.value = true
        const file = options.file
        
        // 转换为Base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = async (e) => {
          const base64Content = e.target.result.split(',')[1]
          const folder = generateFilePath('resumeAuto', '')
          
          await ensureLogin()
          
          const res = await app.callFunction({
            name: 'admin-file-upload',
            data: {
              fileContent: base64Content,
              fileName: file.name,
              folder
            }
          })
          
          if (res.result && res.result.code === 0) {
            form.fileidPdf = res.result.data.fileId
            ElMessage.success('PDF文档上传成功')
          } else {
            ElMessage.error(res.result?.message || 'PDF文档上传失败')
          }
        }
      } catch (error) {
        console.error('上传PDF文档失败:', error)
        ElMessage.error('PDF文档上传失败')
      } finally {
        pdfUploading.value = false
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            submitting.value = true
            
            // 确保用户已登录
            await ensureLogin()
            
            // 准备提交数据
            const submitData = {
              title: form.title,
              template: form.template,
              tags: form.tagsArray.join(','),
              imgPreview: form.imgPreview,
              fileid: form.fileid,
              fileidPdf: form.fileidPdf,
              enable: form.enable
            }
            
            // 如果是编辑模式，添加ID
            if (isEdit.value && form._id) {
              submitData._id = form._id
            }
            
            // 如果有ID字段，也添加进去
            if (form.id) {
              submitData.id = form.id
            }
            
            // 调用云函数
            const res = await app.callFunction({
              name: 'admin-recommend-template-crud',
              data: {
                action: isEdit.value ? 'update' : 'create',
                data: submitData
              }
            })
            
            if (res.result && res.result.code === 0) {
              ElMessage.success(isEdit.value ? '编辑推荐模板成功' : '新增推荐模板成功')
              dialogVisible.value = false
              resetForm()
              emit('refresh')
            } else {
              ElMessage.error(res.result?.message || (isEdit.value ? '编辑推荐模板失败' : '新增推荐模板失败'))
            }
          } catch (error) {
            console.error(isEdit.value ? '编辑推荐模板失败:' : '新增推荐模板失败:', error)
            ElMessage.error(isEdit.value ? '编辑推荐模板失败' : '新增推荐模板失败')
          } finally {
            submitting.value = false
          }
        } else {
          return false
        }
      })
    }
    
    // 标签相关方法
    const showTagInput = () => {
      inputTagVisible.value = true
      nextTick(() => {
        tagInputRef.value.focus()
      })
    }
    
    const handleTagClose = (tag) => {
      form.tagsArray = form.tagsArray.filter(t => t !== tag)
    }
    
    const handleTagConfirm = () => {
      if (inputTagValue.value) {
        if (form.tagsArray.length >= 5) {
          ElMessage.warning('最多只能添加5个标签')
        } else if (form.tagsArray.includes(inputTagValue.value)) {
          ElMessage.warning('标签已存在')
        } else {
          form.tagsArray.push(inputTagValue.value)
        }
      }
      inputTagVisible.value = false
      inputTagValue.value = ''
    }
    
    return {
      formRef,
      tagInputRef,
      dialogVisible,
      isEdit,
      form,
      rules,
      tagOptions,
      wordUploading,
      pdfUploading,
      submitting,
      inputTagVisible,
      inputTagValue,
      handleClose,
      showTagInput,
      handleTagClose,
      handleTagConfirm,
      beforeImageUpload,
      beforeWordUpload,
      beforePdfUpload,
      uploadPreviewImage,
      uploadWordFile,
      uploadPdfFile,
      submitForm
    }
  }
}
</script>

<style>
.el-dialog {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
  background: rgba(0, 19, 47) !important;
  overflow: hidden !important;
}
.el-dialog__title {
  color: #00c0ff !important;
  font-weight: bold !important;
}
.el-input__count-inner{
  background: inherit !important;
}
</style>
<style scoped>
.template-form {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
  color: #00c0ff;
}

.datav-form-container {
  width: 100%;
  height: auto;
  padding: 10px;
  background-color: rgba(0, 19, 47, 0.8);
}

:deep(.dv-border-box-8) {
  --dv-bb8-color: rgba(0, 192, 255, 0.6);
}

.datav-dialog-footer-box {
  width: 100%;
  height: 50px;
}

.datav-dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

:deep(.datav-dialog) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
  background: rgba(0, 19, 47) !important;
  overflow: hidden !important;
}

:deep(.datav-dialog .el-dialog) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
}

:deep(.datav-dialog .el-dialog__header) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-bottom: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 15px 20px !important;
  position: relative;
}

.dialog-header-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 30px;
  z-index: 1;
}

.dialog-footer-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 30px;
  z-index: 1;
}

:deep(.datav-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #00c0ff !important;
}

:deep(.datav-dialog .el-dialog__body) {
  background-color: rgba(0, 19, 47, 0.8) !important;
  padding: 20px !important;
  color: #00c0ff !important;
}

:deep(.datav-dialog .el-dialog__footer) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-top: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 10px 20px !important;
  height: 70px;
}

:deep(.el-overlay) {
  background-color: rgba(0, 10, 30, 0.7) !important;
  backdrop-filter: blur(3px);
}

:deep(.dv-border-box-1) {
  --dv-bb1-color: rgba(0, 192, 255, 0.5);
}

:deep(.el-form-item__label) {
  color: #00c0ff !important;
}

:deep(.el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: none !important;
}

:deep(.el-input__inner) {
  color: #ffffff !important;
}

:deep(.el-textarea__inner) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  color: #ffffff !important;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
}

.template-image-uploader {
  border: 1px dashed rgba(0, 192, 255, 0.5);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 30, 60, 0.4);
}

.template-image-uploader:hover {
  border-color: #00c0ff;
  background-color: rgba(0, 30, 60, 0.6);
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-uploader-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #00c0ff;
  font-size: 14px;
}

.image-uploader-placeholder .el-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.image-tips {
  font-size: 12px;
  margin-top: 5px;
  color: rgba(0, 192, 255, 0.7);
}

.form-tip {
  font-size: 12px;
  color: rgba(0, 192, 255, 0.7);
  margin-top: 5px;
}

.file-info {
  display: flex;
  align-items: center;
  color: #00c0ff;
  margin-top: 10px;
}

.file-info .el-icon {
  margin-right: 5px;
}

:deep(.el-button.tech-button--primary) {
  background-color: rgba(0, 192, 255, 0.2) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #00c0ff !important;
}

:deep(.el-button.tech-button--primary:hover) {
  background-color: rgba(0, 192, 255, 0.4) !important;
  border-color: #00c0ff !important;
  color: #ffffff !important;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.5) !important;
}

:deep(.el-button.tech-button) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border-color: rgba(0, 192, 255, 0.3) !important;
  color: rgba(0, 192, 255, 0.8) !important;
}

:deep(.el-button.tech-button:hover) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #ffffff !important;
}

.tag-item {
  margin-right: 5px;
  margin-bottom: 5px;
  background-color: rgba(0, 30, 60, 0.6);
  border-color: rgba(0, 192, 255, 0.5);
  color: #ffffff;
}

.tag-input {
  width: 120px;
  margin-right: 10px;
  vertical-align: bottom;
}

.button-new-tag {
  margin-left: 5px;
  background-color: rgba(0, 40, 80, 0.5);
  border-color: rgba(0, 192, 255, 0.3);
  color: #00c0ff;
}

.button-new-tag:hover {
  background-color: rgba(0, 60, 120, 0.5);
  border-color: rgba(0, 192, 255, 0.5);
  color: #ffffff;
}

.file-upload-container {
  display: flex;
  align-items: center;
}

.file-uploaded {
  display: flex;
  align-items: center;
  margin-left: 10px;
  color: #00c0ff;
}

.file-uploaded .el-icon {
  margin-right: 5px;
}

.tech-switch :deep(.el-switch__label) {
  color: rgba(0, 192, 255, 0.7);
}

.tech-switch :deep(.el-switch__core) {
  border-color: rgba(0, 192, 255, 0.3);
  background-color: rgba(0, 40, 80, 0.5);
}

.tech-switch :deep(.el-switch.is-checked .el-switch__core) {
  border-color: #00c0ff;
  background-color: #00c0ff;
}

.datav-modal {
  background-color: rgba(0, 10, 30, 0.7) !important;
  backdrop-filter: blur(3px);
}
</style>
